﻿using AutoMapper;
using MediatR;
using SmartCity.BasicData.Api.Application.Commond.Area;
using SmartCity.BasicData.Common;
using SmartCity.BasicData.Domain;
using SmartCity.BasicData.Repo;
using System.Collections.Generic;

namespace SmartCity.BasicData.Api.Application.Handler.Area
{
    public class GetAreaTreeHandler : IRequestHandler<GetAreaTreeCommond, ApiResult<List<AreaTreeDTO>>>
    {
        private readonly IBaseRepository<AreasModel> areaRepo;
        private readonly IMapper mapper;
        private readonly ILogger<GetAreaTreeHandler> logger;

        public GetAreaTreeHandler(IBaseRepository<AreasModel> areaRepo,IMapper mapper,ILogger<GetAreaTreeHandler> logger)
        {
            this.areaRepo = areaRepo;
            this.mapper = mapper;
            this.logger = logger;
        }

        public Task<ApiResult<List<AreaTreeDTO>>> Handle(GetAreaTreeCommond request, CancellationToken cancellationToken)
        {
            ApiResult<List<AreaTreeDTO>> result = new ApiResult<List<AreaTreeDTO>>();
            result.Data = GetTree(0);
            result.Msg = "查询成功!";
            result.Code = Common.Menus.EnumResultCode.Success;  
            return Task.FromResult(result);
        }

        private List<AreaTreeDTO> GetTree(long parentId) { 
            var query = areaRepo.QueryAllAsync().Result.Where(x => x.ParentId == parentId);
            var areaList = mapper.Map<List<AreaTreeDTO>>(query.ToList());
            foreach (var area in areaList) {
                area.Children = GetTree(area.Id);
            }
            return areaList;
        }
    }
}
